package com.springcloud.redisclient.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Component
public class JedisUtil {

	private static Logger logger = LoggerFactory.getLogger(JedisUtil.class);

	//@Value("${spring.redis.host}")
	private static String ADDR="10.2.7.32";

	//@Value("${spring.redis.port}")
	private static int PORT=6379;

	//@Value("${spring.redis.pass}")
	private static String AUTH="";

	//@Value("${spring.redis.max-active}")
	private static int MAX_ACTIVE=8;

	//@Value("${spring.redis.max-idle}")
	private static int MAX_IDLE=8;

	//@Value("${spring.redis.max-wait}")
	private static int MAX_WAIT=0;

	//@Value("${spring.redis.timeout}")
	private static int TIMEOUT = 0;

	private static boolean TEST_ON_BORROW = true;

	private static JedisPool jedisPool = null;

	static {
		try {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(MAX_ACTIVE);
			config.setMaxIdle(MAX_IDLE);
			config.setMaxWaitMillis(MAX_WAIT);
			config.setTestOnBorrow(TEST_ON_BORROW);
			logger.info("ADDR>>"+ADDR+"PORT"+PORT+"TIMEOUT"+TIMEOUT+"AUTH"+AUTH);
			jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取Jedis实例
	 * 
	 * @return
	 */
	public synchronized static Jedis getJedis() {
		try {
			if (jedisPool != null) {
				Jedis resource = jedisPool.getResource();
				return resource;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 释放jedis资源
	 * 
	 * @param jedis
	 */
	public  void returnResource(final Jedis jedis) {
		if (jedis != null) {
			jedisPool.returnResource(jedis);
		}
	}

	/**
	 * 获取redis键值-object
	 * 
	 * @param key
	 * @return
	 */
	public JedisPool getPool() {
		return jedisPool;
	}

	/**
	 * 设置单个值，并设置超时时间
	 * 
	 * @param key
	 *            键
	 * @param value
	 *            值
	 * @param timeout
	 *            超时时间（秒）
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	public String set(String key, String value, Integer timeout) {
		String result = null;

		Jedis jedis = JedisUtil.getJedis();
		if (jedis == null) {
			return result;
		}
		try {
			result = jedis.set(key, value);
			if (null != timeout) {
				jedis.expire(key, timeout);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (null != jedis) {
				jedis.close();
			}
		}
		return result;
	}
	
	public  String setObject(String key, Object object, Integer timeout) {
		String result = null;

		Jedis jedis = JedisUtil.getJedis();
		if (jedis == null) {
			return result;
		}
		try {
			result = jedis.set(key.getBytes(), SerializeUtil.serialize(object));
			if (null != timeout) {
				jedis.expire(key, timeout);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (null != jedis) {
				jedis.close();
			}
		}
		return result;
	}
	
	
	public  Object getObject(String key) {
		byte[] result = null;
		Jedis jedis = JedisUtil.getJedis();
		if (jedis == null) {
			return null;
		}
		try {
			result = jedis.get(key.getBytes());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (null != jedis) {
				jedis.close();
			}
		}
		return SerializeUtil.unserialize(result);
	}


	/**
	 * 获取单个值
	 * 
	 * @param key
	 * @return
	 */
	public  String get(String key) {
		String result = null;
		Jedis jedis = JedisUtil.getJedis();
		if (jedis == null) {
			return result;
		}
		try {
			result = jedis.get(key);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (null != jedis) {
				jedis.close();
			}
		}
		return result;
	}

	/**
	 * 删除redis中数据
	 * 
	 * @param key
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	public  boolean del(String key) {
		Boolean result = Boolean.FALSE;
		Jedis jedis = JedisUtil.getJedis();
		if (null == jedis) {
			return Boolean.FALSE;
		}
		try {
			jedis.del(key);
		} catch (Exception e) {
			logger.error("删除redis数据出错，" + e);
		} finally {
			if (null != jedis) {
				jedis.close();
			}
		}
		return result;
	}

	/**
	 * 追加
	 * 
	 * @param key
	 * @param value
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	public  Long append(String key, String value) {
		Long result = Long.valueOf(0);
		Jedis jedis = JedisUtil.getJedis();
		if (null == jedis) {
			return result;
		}
		try {
			result = jedis.append(key, value);
		} catch (Exception e) {
			logger.error("追加redis数据出错，" + e);
		} finally {
			if (null != jedis) {
				jedis.close();
			}
		}
		return result;
	}

	/**
	 * 检测是否存在
	 * 
	 * @param key
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	public  Boolean exists(String key) {
		Boolean result = Boolean.FALSE;
		Jedis jedis = JedisUtil.getJedis();
		if (null == jedis) {
			return result;
		}
		try {
			result = jedis.exists(key);
		} catch (Exception e) {
			logger.error("检查是否存在出错：，" + e);
		} finally {
			if (null != jedis) {
				jedis.close();
			}
		}
		return result;
	}

	/*
	 * public static void setKeyValue(String key,String value){ Jedis jedis =
	 * new Jedis("10.2.7.32", 6379); try { jedis.set(key, value); } catch
	 * (Exception e) { e.printStackTrace(); }finally{ jedis.close(); } }
	 * 
	 * public static String getValueFromKey(String key){ Jedis jedis = new
	 * Jedis("10.2.7.32", 6379); return jedis.get(key); }
	 */

}
